
(function (win) {
	var http = {};
	var Config = {
		Server: "http://aikj.pro/", 
	};
	var ajaxConfig = {
		action: "",
		method: "POST",
		data: {},
		token: "",
	};
	var getParams = function (data) {
		var list = [];
		for (var item in data) {
			if (item != "action")
				list.push(item + "=" + data[item]);
		}
		var timestamp = new Date().getTime();
		list.push("timestamp=" + timestamp);
		list.sort();
		var params = list.join("&");
		return {
			params: params,
			timestamp: timestamp
		};
	};
	/**
	 * Ajax请求
	 * @param {JSON} 请求参数
	 * @param {Function} 执行成功回调函数
	 * @param {Function} 执行完成回调函数
	 */
	http.ajax = function (params, success, compelete) {
		for (var item in ajaxConfig) {
			params[item] = params[item] || ajaxConfig[item];
		}
		var method = params.method || "POST";
		var action = params.action || "";
		if (action.length < 2) {
			success({
				status: -10000,
				msg: "非法请求"
			});
			return;
		}
		if (method.toUpperCase() == "GET") {
			this.get(action, params.data, success, compelete, params.token);
		} else {
			this.post(action, params.data, success, compelete, params.token);
		}
	};

	/**
	 * Get请求
	 * @param {String} 请求action名称
	 * @param {JSON} GET数据
	 * @param {Function} 执行成功回调函数
	 * @param {Function} 执行完成回调函数
	 */
	http.get = function (action, data, success, compelete, token) {
		var params = getParams(data);
		var url = [];
		url.push(Config.Server);
		url.push("/Tools/AI.ashx?action=");
		url.push(action);
		url.push("&");
		url.push(params.params);
		var obj = new XMLHttpRequest(); // XMLHttpRequest对象用于在后台与服务器交换数据          
		obj.open('GET', url.join(""), true);
		obj.setRequestHeader("Authorization", "Basic " + token);
		obj.onreadystatechange = function () {
			if (compelete) {
				compelete(obj.readyState);
			}
			if (obj.readyState == 4 && obj.status == 200 || obj.status == 304) {
				var ret = JSON.parse(obj.responseText);
				console.log('get++++url++++'+url.join(""));
				console.log('get++++返回的数据+++++'+JSON.stringify(ret));
				if (success)
					success(ret);
			} else if (obj.status == 401) {				
//				localStorage.setItem("IsLogin", "0")
				//ToDo:Token认证失败，需要重新登录
			} else if (obj.status == 500) {
				//ToDo:系统后台报错
			}
		};
		obj.send();
	};

	/**
	 * Post请求
	 * @param {String} 请求action名称
	 * @param {JSON} POST数据
	 * @param {Function} 执行成功回调函数
	 * @param {Function} 执行完成回调函数
	 */
	http.post = function (action, data, success, compelete, token) {
		var params = getParams(data);
		var url = [];
		url.push(Config.Server);
		url.push("/Tools/AI.ashx?action=");
		url.push(action);
		var obj = new XMLHttpRequest();
		obj.open("POST", url.join(""), true);
		obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		obj.setRequestHeader("Authorization", "Basic " + token);
		obj.onreadystatechange = function () {
			if (compelete) {
				compelete(obj.readyState);
			}
			if (obj.readyState == 4 && (obj.status == 200 || obj.status == 304)) { // 304未修改
				var ret = JSON.parse(obj.responseText);
				console.log('post++++++url++++'+url.join(""));
				console.log('post+++++参数+++++'+JSON.stringify(params.params));
				console.log('post+++++返回的数据++++++'+JSON.stringify(ret));
				if(String(ret.status)=='-99'){
					_toast('登录已经过期，请重新登录');
        			localStorage.setItem('ai_user','');
        			setTimeout(function(){
        				var op = {
					        'backButtonAutoControl': 'close', //返回是关闭当前页
					        'animationOptimization': 'none', //不优化
					    };
					    var web = plus.webview.create('login.html', 'login', op);
					    web.addEventListener("loaded", function() {
					    	web.show('none');
					    }, false);
        			},1000);
				}else{
					success.call(this, ret);
				}
			} else if (obj.status == 401) {
//				localStorage.setItem("IsLogin", "0")
				//ToDo:Token认证失败，需要重新登录
			} else if (obj.status == 500) {
				//ToDo:系统后台报错
			}
		};
		obj.send(params.params);
	};
	win.HTTP = http;
})(window);



//验证手机号正则
var _checkMobile = function(sMobile) {
    if (!(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(sMobile))) {
        return false;
    } else {
        return true;
    }
}

//转换时间戳
var _date = function(timestamp) {
    if (!timestamp) {
        return "";
    }
    var date;
    //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    if (String(timestamp).length == 10) {
        date = new Date(Number(timestamp) * 1000);
    }
    if (String(timestamp).length == 13) {
        date = new Date(Number(timestamp));
    }
    var Y = date.getFullYear() + "-";
    var M =
        (date.getMonth() + 1 < 10 ?
            "0" + (date.getMonth() + 1) :
            date.getMonth() + 1) + "-";
    var D = date.getDate() + " ";
    var h = date.getHours() + ":";
    if (date.getHours() < 10) {
        h = '0' + date.getHours() + ":";
    }
    var m = date.getMinutes() + ":";
    if (date.getMinutes() < 10) {
        m = '0' + date.getMinutes() + ":";
    }
    var s = date.getSeconds();
    if (date.getSeconds() < 10) {
        s = '0' + date.getSeconds();
    }
    return Y + M + D + h + m + s;
};
//关闭页面
var _close = function() {
    var web = plus.webview.currentWebview();
    web.close();
};
//乘法
var _accMul = function(arg1, arg2) {
    var m = 0,
        s1 = arg1.toString(),
        s2 = arg2.toString();
    try { m += s1.split(".")[1].length } catch (e) {}
    try { m += s2.split(".")[1].length } catch (e) {}
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
};
//钱分转换为元
var _money = function(val) {
    var judge = String(val);
    if (judge == "undefined" || judge == "null") {
        return 0.0;
    }
    var priceStr = String(parseFloat(parseInt(val) / 100));
    var index = priceStr.indexOf(".");
    if (index != -1) {
        var handle = priceStr.slice(index + 1);
        if (handle.length == 1) {
            priceStr = priceStr + "0";
        }
    } else {
        priceStr = priceStr + ".00";
    }
    return priceStr;
};
/*
	content:密码错误(提示内容)
	position:center(提示的垂直位置)
*/
var _toast = function(content, position) {
    if (!position) {
        position = 'center';
    }
    plus.nativeUI.toast(content, {
        verticalAlign: position
    });
};

// 复制到剪贴板
var _copy = function(text) {
    var osName = plus.os.name;
    if (plus.os.name == "Android") {
        var Context = plus.android.importClass("android.content.Context");
        var main = plus.android.runtimeMainActivity();
        var clip = main.getSystemService(Context.CLIPBOARD_SERVICE);
        plus.android.invoke(clip, "setText", text);
    } else if (osName == "iOS") {
        var UIPasteboard = plus.ios.importClass("UIPasteboard");
        var generalPasteboard = UIPasteboard.generalPasteboard();
        // 设置/获取文本内容:
        generalPasteboard.setValueforPasteboardType(text, "public.utf8-plain-text");
    }
};

//截取6位
var _toFixed = function(str1, num) {
    var str = String(str1);
    function hanZeo(z) {
        var zeo = '';
        for (var i = 0; i < z; i++) {
            zeo += '0';
        }
        return zeo;
    }
    var arr = str.split('.');
    if (arr[1]) {
        if (arr[1].length >= num) {
            return arr[0] + '.' + arr[1].slice(0, num);
        } else {
            return arr[0] + '.' + arr[1] + hanZeo(num - arr[1].length);
        }
    } else {
        return str + '.' + hanZeo(num);
    }
};

//判断输入的是小数或整数
var _ifNum = function(val, type) {
    // 返回true:满足   false:不满足
    // type:int/float
    if (!parseFloat(val)) {
        return false;
    }
    var str = String(val);
    var point = 0;
    var off = true;
    for (var i = 0; i < str.length; i++) {
        if (isNaN(Number(str[i]))) {
            //不是数字
            if (str[i] == '.') {
                point++;
            } else {
                off = false;
                break;
            }
        }
    }
    if (type == 'int') {
        (off && !point) ? '' : off = false;
    }
    if (type == 'float') {
        (off && point <= 1 && str[str.length - 1] != '.' && str[0] != '.') ? '' : off = false;
    }
    return off;
};

//联系客服
var _findWe=function(){
    if (plus.os.name.toLowerCase() == 'android') {
        var main = plus.android.runtimeMainActivity();
        var Intent = plus.android.importClass('android.content.Intent');
        var Uri = plus.android.importClass('android.net.Uri');
        var intent = new Intent(Intent.ACTION_VIEW, Uri.parse('mqqwpa://im/chat?chat_type=wpa&uin=' + SERVICEQQ));
        main.startActivity(intent);
    } else if (plus.os.name.toLowerCase() == "ios") {
        plus.runtime.launchApplication({
            action: "mqq://im/chat?chat_type=wpa&uin=" + SERVICEQQ + "&version=1&src_type=web"
        }, function(e) {
            plus.nativeUI.confirm("检查到您未安装qq，请先到安装QQ", function(i) {
                if (i.index == 0) {
                    iosAppstore("itunes.apple.com/cn/app/mqq/");
                }
            });
        });
    }
};

var _bas64Post = function(url, json, cal) {
    function handleBase64(data) {
        console.log('原没加密的json========');
        console.log(JSON.stringify(data));
        var base = new Base64();
        var list = {};
        for (var key in data) {
            var val = null;
            if (typeof data[key] == 'object' || typeof data[key] == 'number') {
                val = JSON.stringify(data[key]);
            } else {
                val = data[key];
            }
            list[base.encode(key)] = base.encode(val);
        }
        return list;
    }
    _post(url, handleBase64(json), cal);
};

var _post = function(url, json, cal) {
    console.log('url++++++' + url);
    console.log('post参数+++++++++');
    console.log(JSON.stringify(json));
    var obj = new XMLHttpRequest();
    obj.open('post', url, true);
    obj.onreadystatechange = function() {
        if (obj.readyState == 4 && obj.status == 200 || obj.status == 304) {
            var ret = JSON.parse(obj.responseText);
            console.log('post返回的结果++++++');
            console.log(JSON.stringify(ret));
            cal(ret);
        }
    };
    obj.send(JSON.stringify(json));
}

//打开页面
var _openHref = function(json) {
    var animate = json.animate ? json.animate : 'slide-in-right';
    var op = {
        'backButtonAutoControl': 'close', //返回是关闭当前页
        'animationOptimization': 'none', //不优化
        statusbar: {
            background: json.bg ? json.bg : '#1d618a'
        },
        popGesture: 'close'
    };
    app.$data.jiazai = true;
    var web = plus.webview.create(json.url, json.id, op);
    web.addEventListener("loaded", function() {
        setTimeout(function() {
            app.$data.jiazai = false;
            web.show(animate);
        }, 200);
    }, false);
    return web;
}

//联系我们
var SERVICEQQ='728864588';

//登录
var LOGIN='ai_login';

//自动登录
var SESSIONLOGIN='ai_sessionLogin';

//注册
var REGISET='ai_register';

//忘记密码
var FORGETPAS='ai_forget';

//首页
var INDEXDATA='ai_index';

//获取广告
var GETARTICLE='ai_allarticle';

//退出登录
var CLOSELOGIN='ai_clearinfo';

//发送验证码
var SENDCODE='ai_sendsms';

//获取余额
var GETBAN='ai_balance';

//导入API(绑定交易所账户)
var BINDTOKEN='ai_bindtoken';

//更新
var UPDATAURL='ai_ToUpdate';

//绑定激活码
var BINDACCODE='ai_bindkey';

//挖矿
var WAKUANG='ai_mining';

//退出挖矿
var CLOSEWAKUAGN='ai_exittask';

//分享调用下载地址来生成二维码
var MASKQR='ai_download';

//关于AI机器人
var INTROAI='ai_getnotice';

//最大挖矿量
var MAXWAKUANG='ai_config';

//历史成交
var HISTORYTRAN='ai_tradelog';

//收益查询
var QUERYMONEY='ai_querymoney'

//激活信息
var INVIINFO='ai_keyinfo';



//激活的相关信息  进不去
//收益查询  有问题
//历史记录也差   赛选有问题
